package tcp_proxy_middleware

import (
	"fmt"
	"gitee.com/zhoulvvv/my_go_gateway/dao"
	"gitee.com/zhoulvvv/my_go_gateway/public"
	"strings"
)

// TCP IP 白名单中间件
func TCPWhiteListModeMiddleware() func(c *TcpSliceRouterContext) {
	return func(c *TcpSliceRouterContext) {
		serviceInterface := c.Get("service")
		if serviceInterface == nil {
			c.Conn.Write([]byte("【服务不存在】service not found"))
			c.Abort()
			return
		}
		service := serviceInterface.(*dao.ServiceDetail)
		// 获取IP白名单集合
		ipList := []string{}
		if service.AccessControl.WhiteList != "" {
			ipList = strings.Split(service.AccessControl.WhiteList, ",")
		}
		splits := strings.Split(c.Conn.RemoteAddr().String(), ":")
		clientIP := ""
		if len(splits) == 2 {
			clientIP = splits[0]
		}
		// 判断是否开启权限校验
		if service.AccessControl.OpenAuth == 1 && len(ipList) > 0 {
			if !public.InStringsSlice(ipList, clientIP) {
				c.Conn.Write([]byte(fmt.Sprintf("%s 不存在 ip 白名单中", clientIP)))
				c.Abort()
				return
			}
		}
		c.Next()
	}
}
